jsPlumb.importDefaults({
	//Overlays:[
	//	["label",{cssClass:"labelcss"}]
	//]
});
var isStart = true;
var isEnd = true;
//基本连接线样式
var connectorPaintStyle = {
	lineWidth: 4,
	strokeStyle: "#61B7CF",
	joinstyle: "round",
	outlineColor: "white",
	outlineWidth: 2
};
// 鼠标悬浮在连接线上的样式
var connectorHoverStyle = {
	lineWidth: 4,
	strokeStyle: "#216477",
	outlineWidth: 2,
	outlineColor: "white"
};
//鼠标悬停在endpoint样式
var endpointHoverStyle = {
        strokeStyle:"red",
        fillStyle: "transparent",
		radius: 4,
		lineWidth: 2
    };
var a = 0;
var hollowCircle = {
	/*endpoint: ["Dot", {
		radius: 8
	}], //端点的形状 ,在此处无效？？？
	*/
	connectorStyle: connectorPaintStyle, //连接线的颜色，大小样式
	connectorHoverStyle: connectorHoverStyle,
	//endpointHoverStyle: endpointHoverStyle,
	paintStyle: {
		strokeStyle: "#1e8151",
		fillStyle: "transparent",
		radius: 4,
		lineWidth: 2
	}, //端点的颜色样式，和形状
	//anchor: "AutoDefault",
	isSource: true, //是否可以拖动（作为连线起点）
	connector: ["Flowchart", {
		stub: [40, 60],
		gap: 10,
		cornerRadius: 5,
		alwaysRespectStubs: true
	}], //连接线的样式种类有[Bezier],[Flowchart],[StateMachine ],[Straight ]
	isTarget: true, //是否可以放置（连线终点）
	maxConnections: -1, // 设置连接点最多可以连接几条线
	connectorOverlays: [
		["Arrow", {
			width: 10,
			length: 10,
			location: 1
		}],
		["Custom", {
			create: function(component) {
				a++;
				return $("<select id='myDropDown" + a + "' class='myDropDown' style='font-size:12px'></select>");
			},
			location: 0.2,
			id: "customOverlay"
		}]
	]
};

var loadStyle = {

}

function doubleclick(id) { //修改节点名称
	$(id).dblclick(function() {
		var text = $(this).text();
		$(this).html("");
		$(this).append("<input type='text' value='" + text + "' />");
		$(this).mouseleave(function() {
			$(this).html($("input[type='text']").val());
		});
	});
}

function save() { //保存，getAllConnentions()获取所有连接，$.each()遍历
	var connects = []; //将所有连线信息保存在connects中
	$.each(jsPlumb.getAllConnections(), function(idx, connection) {
		//	console.log(idx);
		var SourceEndpoint = connection.endpoints[0].anchor.type; //获取源的endpoint位置
		var TargetEndpoint = connection.endpoints[1].anchor.type; //获取目标的endpoint位置
		var labelText = connection.getLabel(); //获取线上标签
		//var b =connection.getOverlays();
		//console.log(b.customOverlay._jsPlumb.div.value);//获取线上select值
		//var ConnectionSelectText = connection.getOverlays().customOverlay._jsPlumb.div.value;
		connects.push({
			ConnectionId: connection.id,
			SourceId: connection.sourceId,
			TargetId: connection.targetId,
			SourceEndpoint: SourceEndpoint,
			TargetEndpoint: TargetEndpoint,
			SourceText: connection.source.textContent,
			TargetText: connection.target.textContent,
			ConnectionLabelText: labelText,
			//ConnectionSelectText: ConnectionSelectText
		});
	});
	console.log(connects);
	var blocks = []; //所有DOM节点信息保存在blocks中
	$("#right .node").each(function(idx, elem) {
		var $elem = $(elem);
		//console.log($elem);
		//console.log($elem.html());
		blocks.push({
			BlockId: $elem.attr('id'),
			BlockText: $elem.context.innerText,
			BlockContent: $elem.html(),
			BlockX: parseInt($elem.css("left"), 10),
			BlockY: parseInt($elem.css("top"), 10)
		});
	});
	//console.log(blocks);
	var serliza = JSON.stringify(connects) + "&" + JSON.stringify(blocks);
	console.log(serliza);
	//var obj = JSON.parse(str); //由JSON字符串转换为JSON对象
	//var last=JSON.stringify(obj); //将JSON对象转化为JSON字符
}

function load() { /*此处的数据应该是从后台读取的*/
	var htmlText = "";
	var conn = "";
	var connectsData = [{
		ConnectionId: "con_16",
		SourceId: "state_start1",
		TargetId: "state_flow1",
		SourceEndpoint: "BottomCenter",
		TargetEndpoint: "RightMiddle",
		SourceText: "开始",
		TargetText: "判断1",
		ConnectionLabelText: "1",
		ConnectionSelectText: "请选择"
	}, {
		ConnectionId: "con_31",
		SourceId: "state_flow1",
		TargetId: "state_decide1",
		SourceEndpoint: "BottomCenter",
		TargetEndpoint: "LeftMiddle",
		SourceText: "判断1",
		TargetText: "流程1",
		ConnectionLabelText: "2",
		ConnectionSelectText: "语音1"
	}, {
		ConnectionId: "con_46",
		SourceId: "state_decide1",
		TargetId: "state_decide2",
		SourceEndpoint: "RightMiddle",
		TargetEndpoint: "LeftMiddle",
		SourceText: "流程1",
		TargetText: "流程2",
		ConnectionLabelText: "3",
		ConnectionSelectText: "语音2"
	}, {
		ConnectionId: "con_53",
		SourceId: "state_decide2",
		TargetId: "state_end1",
		SourceEndpoint: "RightMiddle",
		TargetEndpoint: "TopCenter",
		SourceText: "流程2",
		TargetText: "结束",
		ConnectionLabelText: "4",
		ConnectionSelectText: "请选择"
	}]
	var blockData = [{
		BlockId: "state_start1",
		BlockText: "开始",
		BlockContent: "开始<img src='/my/img/close.jpg' style='position: absolute; left: 78px; top: -10px; display: none;'>",
		BlockX: 463,
		BlockY: 73
	}, {
		BlockId: "state_flow1",
		BlockText: "判断1",
		BlockContent: "判断1<img src='/my/img/close.jpg' style='position: absolute; left: 78px; top: -10px; display: none;'>",
		BlockX: 111,
		BlockY: 159
	}, {
		BlockId: "state_decide1",
		BlockText: "流程1",
		BlockContent: "流程1<img src='/my/img/close.jpg' style='position: absolute; left: 78px; top: -10px; display: none;'>",
		BlockX: 183,
		BlockY: 318
	}, {
		BlockId: "state_decide2",
		BlockText: "流程2",
		BlockContent: "流程2<img src='/my/img/close.jpg' style='position: absolute; left: 78px; top: -10px; display: none;'>",
		BlockX: 450,
		BlockY: 315
	}, {
		BlockId: "state_end1",
		BlockText: "结束",
		BlockContent: "结束<img src='/my/img/close.jpg' style='position: absolute; left: 78px; top: -10px; display: none;'>",
		BlockX: 680,
		BlockY: 319
	}]

	if (blockData.length > 0) {
		blockData.forEach(function(item) {
			if (item.BlockText == "开始" || item.BlockText == "结束") {
				htmlText = "<div class='node radius' id='" + item.BlockId + "'style='left:" + item.BlockX + "px;top:" + item.BlockY + "px;' >" + item.BlockContent + "</div>";
				$("#right").append(htmlText);
				if (item.BlockText == "开始") {
					isStart = false;
					jsPlumb.addEndpoint(item.BlockId, {
						anchors: "BottomCenter",
						isTarget: false,
					}, hollowCircle);
				}
				if (item.BlockText == "结束") {
					isEnd = false;
					jsPlumb.addEndpoint(item.BlockId, {
						anchors: "TopCenter",
						isSource: false
					}, hollowCircle);
				}

			} else {
				htmlText = "<div class='node' id='" + item.BlockId + "'style='left:" + item.BlockX + "px;top:" + item.BlockY + "px;' >" + item.BlockContent + "</div>";
				$("#right").append(htmlText);
				jsPlumb.addEndpoint(item.BlockId, {
					anchors: "TopCenter"
				}, hollowCircle);
				jsPlumb.addEndpoint(item.BlockId, {
					anchors: "RightMiddle"
				}, hollowCircle);
				jsPlumb.addEndpoint(item.BlockId, {
					anchors: "BottomCenter"
				}, hollowCircle);
				jsPlumb.addEndpoint(item.BlockId, {
					anchors: "LeftMiddle"
				}, hollowCircle);

			}
			jsPlumb.draggable(item.BlockId);
			$("#" + item.BlockId).draggable({
				containment: "parent",
			});
			doubleclick("#" + item.BlockId);
		})

		connectsData.forEach(function(ite) {          //连线
			jsPlumb.connect({
				source: ite.SourceId,
				target: ite.TargetId,
				anchors: [ite.SourceEndpoint, ite.TargetEndpoint],
				endpoint: ["Blank", {                 //端点样式，此处设置为空白
					strokeStyle: "#1e8151",
					fillStyle: "transparent",
					radius: 4,
					lineWidth: 2
				}],
				//endpointHoverStyle: endpointHoverStyle,
				connector: ["Flowchart", {
					stub: [40, 60],
					gap: 10,
					cornerRadius: 5,
					alwaysRespectStubs: true
				}],                                    //此处的hoverStyle和paintStyle参数名与endpoint不太一样
				hoverPaintStyle:connectorHoverStyle,   //连线hoverStyle
			 	paintStyle: connectorPaintStyle,        //连线Style
				
				overlays: [
					["Arrow", {
						width: 10,
						length: 10,
						location: 1
					}],
					["Label", {
						label: ite.ConnectionLabelText
					}],
					["Custom", {
						create: function(component) {
							console.log(component);
							a++;
							console.log(ite.ConnectionSelectText);
							if (ite.ConnectionSelectText == '语音1') {

								return $("<select id='myDropDown" + a + "' class='myDropDown' style='font-size:12px'> " +
									"<option value='none'>请选择</option>" +
									"<option value='语音1' selected='selected'>语音1</option>" +
									"<option value='语音2'>语音2</option>" +
									+"</select>");
							} else if (ite.ConnectionSelectText == '语音2') {
								return $("<select id='myDropDown" + a + "' class='myDropDown' style='font-size:12px'> " +
									"<option value='none'>请选择</option>" +
									"<option value='语音1' >语音1</option>" +
									"<option value='语音2' selected='selected'>语音2</option>" +
									+"</select>");
							} else if (ite.ConnectionSelectText == '请选择') {
								return $("<select id='myDropDown" + a + "' class='myDropDown' style='font-size:12px'> " +
									"<option value='none' selected='selected'>请选择</option>" +
									"<option value='语音1'>语音1</option>" +
									"<option value='语音2'>语音2</option>" +
									+"</select>");
							}
						},
						location: 0.2,
						id: "customOverlay"
					}]
				]
			});
		})
	}
}

$(document).ready(
	function() {
		var labname;
		var i = 0;
		//j = 0,
		//k = 0,
		//l = 0;

		var id, nodeText;

		$("#left").children().draggable({
			helper: "clone",
			scope: "ss"
		});

		$("#right").droppable({
			scope: "ss",
			drop: function(event, ui) {
				var left = parseInt(ui.offset.left - $(this).offset().left);
				var top = parseInt(ui.offset.top - $(this).offset().top);
				var name = ui.draggable[0].id;
				switch (name) {
					case "node1":
						i = Math.uuid(8, 10); //生成一个8位的10进制ID
						console.log(i);
						//	i++;
						if (!isStart) {
							alert("只能有一个开始节点");
							break;
						} else {
							isStart = false;
							id = "state_start" + i;
							nodeText = $(ui.helper).html();
							$(this).append('<div class="node" style="border-radius: 25em"  id="' + id + '" >' + nodeText + '</div>');
							$("#" + id).css("left", left).css("top", top);
							var e = jsPlumb.addEndpoint(id, {
								anchors: "BottomCenter",
								isTarget: false,
								connectorOverlays: [
									["Arrow", {
										width: 10,
										length: 10,
										location: 1
									}],
									["Custom", {
										create: function(component) {
											a++;
											return $("<select id='myDropDown" + a + "' class='myDropDown' style='font-size:12px'></select>");
										},
										location: 0.8,
										id: "customOverlay"
									}]
								]
							}, hollowCircle);

							jsPlumb.draggable(id);
							$("#" + id).draggable({
								containment: "parent",
							});
							doubleclick("#" + id);
							break;
						}

					case "node2":
						//j++;
						i = Math.uuid(8, 10);
						id = "state_flow" + i;
						nodeText = $(ui.helper).html();
						$(this).append("<div class='node' id='" + id + "'>" + nodeText + "</div>");
						$("#" + id).css("left", left).css("top", top);
						jsPlumb.addEndpoint(id, {
							anchors: "TopCenter"
						}, hollowCircle);
						jsPlumb.addEndpoint(id, {
							anchors: "RightMiddle"
						}, hollowCircle);
						jsPlumb.addEndpoint(id, {
							anchors: "BottomCenter"
						}, hollowCircle);
						jsPlumb.addEndpoint(id, {
							anchors: "LeftMiddle"
						}, hollowCircle);

						jsPlumb.draggable(id);
						$("#" + id).draggable({
							containment: "parent"
						});
						doubleclick("#" + id);
						break;
					case "node3":
						i = Math.uuid(8, 10);
						id = "state_decide" + i;
						nodeText = $(ui.helper).html();
						$(this).append("<div class='node diamond' id='" + id + "'>" + nodeText + "</div>");
						$("#" + id).css("left", left).css("top", top);
						jsPlumb.addEndpoint(id, {
							anchors: "TopCenter",
						}, hollowCircle);
						jsPlumb.addEndpoint(id, {
							anchors: "RightMiddle"
						}, hollowCircle);
						jsPlumb.addEndpoint(id, {
							anchors: "BottomCenter"
						}, hollowCircle);
						jsPlumb.addEndpoint(id, {
							anchors: "LeftMiddle"
						}, hollowCircle);

						jsPlumb.draggable(id);
						$("#" + id).draggable({
							containment: "parent"
						});
						doubleclick("#" + id);
						break;
					case "node4":
						i = Math.uuid(8, 10);
						if (!isEnd) {
							alert("只能有一个结束节点");
							break;
						} else {
							isEnd = false;
							id = "state_end" + i;
							nodeText = $(ui.helper).html();
							$(this).append('<div class="node" style="border-radius: 25em"  id="' + id + '" >' + nodeText + '</div>');
							$("#" + id).css("left", left).css("top", top);
							jsPlumb.addEndpoint(id, {
								anchors: "TopCenter",
								isSource: false
							}, hollowCircle);

							jsPlumb.draggable(id);
							$("#" + id).draggable({
								containment: "parent"
							});
							doubleclick("#" + id);
							break;
						}
				}
				jsPlumb.repaintEverything();
			}
		});
		$("#right").on("mouseenter", ".node", function() {
			$(this).append('<img src="/my/img/close.jpg" style="position: absolute;" />');
			if ($(this).text() == "开始" || $(this).text() == "结束") {
				$("img").css("left", 78).css("top", 0);
			} else {
				$("img").css("left", 78).css("top", -10);
			}
		});

		$("#right").on("mouseleave", ".node", function() {
			$("img").hide(); //此处不能用remove()，如果用了remove会导致点击img找到的父节点是该div的上层
		});

		$("#right").on("click", "img", function() {
			var str = $(this).parent().attr("id");
			if (confirm("确定删除节点吗?")) {
				if (str.indexOf("start")) { //如果删除的是开始节点
					isStart = true;
				}
				if (str.indexOf("end")) {
					isEnd = true; //如果删除的是结束节点
				}
				$(this).parent().remove(); //删除父节点
				jsPlumb.removeAllEndpoints($(this).parent().attr("id")); //删除父节点的所有连接 
				//jsPlumb.repaintEverything();
			}
		});

		jsPlumb.bind("dblclick", function(conn, originalEvent) { //删除连线
			if (confirm("确定删除连线吗"))
				jsPlumb.detach(conn);
		});

		var voice = ['语音1', '语音2'];
		var len = voice.length;

		var connOverlay = jsPlumb.bind("connection", function(info, originalEvent) { //连线时添加标签名称
			//console.log(originalEvent);
			//console.log(info);
			//console.log(info.connection.getOverlays().customOverlay.getElement().id);//获取select的id

			var connectionOverlayId = info.connection.getOverlays().customOverlay.getElement().id;

			if (originalEvent) { //拖拽连线时
				$("#" + connectionOverlayId).prepend("<option value='none'>请选择</option>");
				voice.forEach(function(item) {
					$("#" + connectionOverlayId).append("<option value='" + item + "'>" + item + "</option>");
				})
				if (info.connection.sourceId == info.connection.targetId) {
					jsPlumb.detach(info.connection);
					alert("不能连接自己！");
				} else {
					labname = prompt("请输入标签", "");
					if (labname) {
						info.connection.setLabel(labname);
					} else {
						info.connection.setLabel(".....");
					}
				}
			} else {                                           //导入数据自动连线时originalEvent为false

			}

		});

		$("#right").on("click", 'div.jsplumb-overlay', function(connOverlay) { //点击标签进行修改
			//console.log(connOverlay.currentTarget._jsPlumb);
			var currentLabel = connOverlay.currentTarget._jsPlumb.label;
			labname = prompt("修改标签", currentLabel);
			if (labname) {
				connOverlay.currentTarget._jsPlumb.setLabel(labname);
			} else if (labname == '') {
				connOverlay.currentTarget._jsPlumb.setLabel(".....");
			}
		});
		/*  进入页面则导入	
		jsPlumb.ready(function() {
    		load();
       	})
       */
	})